<template>
  <div>
    <treeselect
      v-model="categoryId"
      :options="categoryOptions"
      :normalizer="normalizer"
      :show-count="true"
      :placeholder="placeholder"
      :disabled="disabled"
      :clearable="clearable"
      :searchable="searchable"
      noOptionsText="暂无分类"
      noChildrenText="暂无子分类"
      @input="handleChange"
    />
  </div>
</template>

<script>
import { getCategoryOptions } from "@/api/secondclass/category";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "CategorySelect",
  components: { Treeselect },
  props: {
    value: {
      type: [Number, String],
      default: null
    },
    placeholder: {
      type: String,
      default: "请选择活动分类"
    },
    disabled: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: true
    },
    searchable: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      categoryId: null,
      categoryOptions: []
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.categoryId = val;
      }
    }
  },
  created() {
    this.getCategories();
  },
  methods: {
    // 获取活动分类选项
    getCategories() {
      getCategoryOptions().then(response => {
        this.categoryOptions = this.handleCategoryOptions(response.data);
      });
    },
    // 处理活动分类选项数据
    handleCategoryOptions(categories) {
      // 过滤掉停用的分类
      const activeCategories = categories.filter(item => item.status === "0");
      // 构建树形结构
      const buildTree = (items, parentId) => {
        const result = [];
        items.forEach(item => {
          if ((parentId === null && item.parentId === null) || 
              (parentId !== null && item.parentId === parentId)) {
            const children = buildTree(items, item.categoryId);
            if (children.length > 0) {
              item.children = children;
            }
            result.push(item);
          }
        });
        return result;
      };
      return buildTree(activeCategories, null);
    },
    // 转换分类数据结构
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.categoryId,
        label: node.categoryName,
        children: node.children
      };
    },
    // 处理选择变化
    handleChange(val) {
      this.$emit("input", val);
      this.$emit("change", val);
    }
  }
};
</script> 